﻿using BZ.Core.Frm;
using NDK.Motion.Card;
using NDK.Motion.MachineManager;
using NDK.Motion.MachineResources;
using NDK.Motion.Properties;
using NDK.Utils;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Threading;
using System.Windows.Forms;

namespace NDK.Motion.Frm
{
    public partial class Frm_DO : Form
    {
        private static log4net.ILog traceLogger = log4net.LogManager.GetLogger("Frm_DO");

        /// <summary>
        /// 是否实时监控DI状态
        /// </summary>
        public bool isMonitoring = false;
        /// <summary>
        /// 窗体关闭状态
        /// </summary>
        public bool isFrmClosed = false;
        BindingList<OutputSetting> DoBindingList = null;
        //List<OutputModel> DOList = MachineDataManager.Instance.DOList.co;
        private Frm_DO()
        {
            InitializeComponent();
            foreach (var item in MachineDataManager.Instance.DOList)
            {
                if (!cb_CardID.Items.Contains(item.Card.CardID))
                {
                    cb_CardID.Items.Add(item.Card.CardID);
                }
            }
        }
        private static Frm_DO _instance;
        private static readonly object singletonLock = new object();
        public static Frm_DO Instance
        {
            get
            {
                if (_instance == null || _instance.IsDisposed)
                {
                    lock (singletonLock)
                    {
                        if (_instance == null || _instance.IsDisposed)
                        {
                            _instance = new Frm_DO();
                        }
                    }
                }
                return _instance;
            }
        }
        private void Frm_DI_Load(object sender, EventArgs e)
        {
            DoBindingList = new BindingList<OutputSetting>(MachineDataManager.Instance.DOList);
            dgv_DO.DataSource = DoBindingList;
            isFrmClosed = false;
            backgroundWorker1.RunWorkerAsync();
        }

        private void btn_FindDO_BtnClick(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(tb_Name.Text.Trim()))
            {
                dgv_DO.DataSource = new BindingList<OutputSetting>(MachineDataManager.Instance.DOList.FindAll(i => i.Name.Contains(tb_Name.Text.Trim())));
                return;
            }
            if (!string.IsNullOrEmpty(cb_CardID.Text.Trim()))
            {
                dgv_DO.DataSource = new BindingList<OutputSetting>(MachineDataManager.Instance.DOList.FindAll(i => i.Card.CardID.ToString() == cb_CardID.Text.Trim()));
            }
            if (string.IsNullOrEmpty(tb_Name.Text.Trim()) && string.IsNullOrEmpty(cb_CardID.Text.Trim()))
            {
                dgv_DO.DataSource = new BindingList<OutputSetting>(MachineDataManager.Instance.DOList);
            }
        }

        private void ckb_Monitoring_CheckedChanged(object sender, EventArgs e)
        {
            if (ckb_Monitoring.CheckState == CheckState.Checked)
            {
                isMonitoring = true;
            }
            else
            {
                isMonitoring = false;
            }
        }
        /// <summary>
        /// 实时监控DI状态
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            while (isFrmClosed == false)//窗体未关闭时扫描状态
            {
                if (isMonitoring == true)
                {
                    for (int rowIndex = 0; rowIndex < dgv_DO.Rows.Count; rowIndex++)
                    {
                        try
                        {
                            //DataGridView处于编辑状态时，不检查DO状态
                            if (dgv_DO.Rows[rowIndex].IsNewRow) break;
                            if (dgv_DO.Rows[rowIndex].Cells["cName"].IsInEditMode) break;
                            //获取当前行的DO
                            string cardType = dgv_DO.Rows[rowIndex].Cells["cCardType"].Value.ToString();
                            string name = dgv_DO.Rows[rowIndex].Cells["cName"].Value.ToString();
                            string port = dgv_DO.Rows[rowIndex].Cells["cPort"].Value.ToString();
                            int cardId = int.Parse(dgv_DO.Rows[rowIndex].Cells["cCardID"].Value.ToString());
                            string strModuleName = dgv_DO.Rows[rowIndex].Cells["cModuleName"].Value.ToString();

                            OutputSetting outputModel = MachineDataManager.Instance.DOList.Find(i => i.Card.CardID == cardId && i.Port.ToString() == port && i.ModuleName.ToString() == strModuleName
                            && i.Card.CardType == cardType && i.Name == name);
                            //得到DO状态，更新界面状态
                            bool doStatus = outputModel.GetStatus();
                            if (dgv_DO.Rows[rowIndex].Cells["cStatus"].Tag?.ToString().ToUpper() == doStatus.ToString().ToUpper())
                            {
                                continue;//状态没有发生变化,不设置
                            }

                            dgv_DO.Rows[rowIndex].Cells["cStatus"].Value = (doStatus == true) ? Resources.LightOn : Resources.LightOff;
                            dgv_DO.Rows[rowIndex].Cells["cStatus"].Tag = doStatus;
                        }
                        catch (Exception ex)
                        {
                            traceLogger.Error(ex.StackTrace);
                        }
                        Application.DoEvents();
                    }
                }
                Thread.Sleep(50);
            }
        }

        private void dgv_DO_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (isMonitoring == true)
            {
                try
                {
                    //DataGridView处于编辑状态时，不检查DO状态
                    int rowIndex = dgv_DO.CurrentRow.Index;
                    if (dgv_DO.Rows[rowIndex].IsNewRow) return;
                    if (dgv_DO.CurrentCell != dgv_DO.Rows[e.RowIndex].Cells["cSetDO"]) return;
                    //获取点击状态，checkbox=true 设置DO高电平，否则设置低电平

                    //dgv_DO.CurrentCell = null;
                    //string strIsRun = dgv_DO.Rows[rowIndex].Cells["cSetDO"].Value.ToString();
                    //if (strIsRun == string.Empty) return;
                    //bool isRun = bool.Parse(strIsRun);
                    //获取当前行的DO
                    var cellPort = dgv_DO.Rows[rowIndex].Cells["cPort"].Value;
                    var port = cellPort.ToString();

                    var cellCardID = dgv_DO.Rows[rowIndex].Cells["cCardID"];
                    string strCardID = cellCardID.Value.ToString();
                    int cardId = int.Parse(strCardID);

                    var cellcModuleName = dgv_DO.Rows[rowIndex].Cells["cModuleName"];
                    string strModuleName = cellcModuleName.Value.ToString();
                    int moduleName = int.Parse(strModuleName);

                    OutputSetting outputModel = MachineDataManager.Instance.DOList.Find(i => i.Card.CardID == cardId && i.Port.ToString() == port && i.ModuleName.ToString() == strModuleName);
                    //if (isRun)
                    //{
                    //    outputModel.ON();
                    //}
                    //else
                    //{
                    //    outputModel.OFF();
                    //}
                    outputModel.Toggle();
                    dgv_DO.CurrentCell = null;
                }
                catch (Exception ex)
                {
                    traceLogger.Error(ex.StackTrace);
                }
            }
        }

        private void dgv_DO_DataError(object sender, DataGridViewDataErrorEventArgs e)
        {

        }

        private void dgv_DO_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == 22)
            {
                DataGridViewUtils.PasteData(dgv_DO);
            }
        }

        private void btn_Delete_BtnClick(object sender, EventArgs e)
        {
            List<OutputSetting> outputSettingList = new List<OutputSetting>();
            var rows = dgv_DO.SelectedRows;

            if (rows.Count > 0)
            {
                foreach (DataGridViewRow row in rows)
                {
                    //获取当前行的DO
                    string cardType = row.Cells["cCardType"].Value.ToString();
                    string name = row.Cells["cName"].Value.ToString();
                    string port = row.Cells["cPort"].Value.ToString();
                    int cardId = int.Parse(row.Cells["cCardID"].Value.ToString());

                    OutputSetting inputModel = MachineDataManager.Instance.DOList.Find(i => i.Card.CardID == cardId && i.Port.ToString() == port
                    && i.Name == name && i.Card.CardType == cardType);//
                    outputSettingList.Add(inputModel);
                }
                List<string> names = new List<string>();
                foreach (var outputSetting in outputSettingList)
                {
                    names.Add(outputSetting.Name);
                }
                Dlg_Confirm dlg_Confirm = new Dlg_Confirm("提示", $"确定删除{string.Join(",", names)}?");
                DialogResult dialogResult = dlg_Confirm.ShowDialog(this);
                if (dialogResult == DialogResult.OK)
                {
                    foreach (var outputSetting in outputSettingList)
                    {
                        MachineDataManager.Instance.DOList.Remove(outputSetting);
                    }
                }
                dgv_DO.DataSource = new BindingList<OutputSetting>(MachineDataManager.Instance.DOList);
            }
        }

        private void Frm_DO_FormClosing(object sender, FormClosingEventArgs e)
        {
            isFrmClosed = true;
        }

        private void ucBtnExt1_BtnClick(object sender, EventArgs e)
        {
            try
            {
                ICard card = new LCT_M60();
                card.CardType = "LCT_M60";
                OutputSetting output = new OutputSetting("M60", card, 2);
                output.ID = 1;
                output.Name = "M60";
                output.ModuleName = 5;
                output.Port = 2;

                output.EffectiveLevel = EFFECTIVE_LEVEL_ENUM.High;
                MachineDataManager.Instance.DOList.Add(output);

                dgv_DO.DataSource = new BindingList<OutputSetting>(MachineDataManager.Instance.DOList);
            }
            catch (Exception ex) { }
        }

        private void ucBtnExt2_BtnClick(object sender, EventArgs e)
        {
            System.Windows.Forms.OpenFileDialog ofd = new System.Windows.Forms.OpenFileDialog();
            ofd.Filter = "文件|*.txt";
            ofd.Multiselect = true;
            if (ofd.ShowDialog() == DialogResult.OK)
            {
                string loadFileName = ofd.FileName;
                MachineDataManager.Instance.DOList.Clear();
                string[] strings = File.ReadAllLines(loadFileName);
                ICard card = new LCT_M60 ();
                card.CardType = "LCT_M60";
                int index = 0;
                for (int i = 0; i < strings.Length; i++)
                {
                    index++;
                    string[] strings1 = strings[i].Split(new char[] { ':' });
                    if (strings1[0].Equals("null"))
                    {
                        continue;
                    }
                    OutputSetting output = new OutputSetting("M60", card, 2);
                    output.ID = index;
                    output.Name = strings1[0];
                    output.ModuleName = int.Parse(strings1[1]);
                    output.Port = int.Parse(strings1[2]);

                    output.EffectiveLevel = EFFECTIVE_LEVEL_ENUM.High;
                    MachineDataManager.Instance.DOList.Add(output);
                    dgv_DO.DataSource = new BindingList<OutputSetting>(MachineDataManager.Instance.DOList);
                }
            }
        }
    }
}
